import { ref } from 'vue';
import { io } from "socket.io-client";

export function useWebSocket(url) {
    const socket = io(url);
    const tradeInfo = ref({});
    const userPositions = ref([]);

    socket.on('connect', () => {
        console.log('Connected to server');
    });

    socket.on('update_tickers', (updateData) => {
        tradeInfo.value = updateData.data[0];
    });

    socket.on('user_positions', (positionsData) => {
        if (positionsData.data) {
            userPositions.value = positionsData.data;
        } else {
            console.error('Error:', positionsData.error);
        }
    });

    socket.on('disconnect', () => {
        console.log('Disconnected from server');
    });

    const queryUserPositions = (queryData) => {
        socket.emit('query_user_positions', queryData);
    };

    const disconnectSocket = () => {
        socket.disconnect();
    };

    return { tradeInfo, userPositions, queryUserPositions, disconnectSocket };
}
